package com.example.demo04.services;

import cn.hutool.http.HttpResponse;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.example.demo04.entity.pojo.AdvancedGeneralPo;
import com.example.demo04.until.RequestUtil;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author taritari
 * @date 2023-10-22 20:02
 * @description
 */
@Service
public class BaiDuApiService {

    public String getToken(){
        HttpResponse post = RequestUtil.post("https://aip.baidubce.com/oauth/2.0/token?client_id=***&client_secret=***&grant_type=client_credentials", "");
        String body = post.body();
        JSONObject token = JSON.parseObject(body);
        String accessToken = token.getString("access_token");
        return accessToken;
    }

    public List<AdvancedGeneralPo> getAdvanceGeneral(String url){
        String params = "url="+url;
        HttpResponse post = RequestUtil.post("https://aip.baidubce.com/rest/2.0/image-classify/v2/advanced_general?access_token=" + getToken(), params);
        // 使用JSON.toJSONString()将Object转为json字符串
        JSONObject jsonObject = JSON.parseObject(post.body());
        Object result = jsonObject.get("result");
        List<AdvancedGeneralPo> advancedGeneralPos = JSONObject.parseArray(result.toString(), AdvancedGeneralPo.class);
        return advancedGeneralPos;
    }
}
